package com.hrhx.springboot.service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFSDBFile;

@Service
public class GridFsService {
	
	@Autowired
	private GridFsTemplate gridFsTemplate;
	
	public void saveFs() throws FileNotFoundException{
		DBObject metaData = new BasicDBObject();
		metaData.put("user", "alex");
		InputStream inputStream = new FileInputStream("/Users/admin/Downloads/cnarea.png"); 
		String id = gridFsTemplate.store(inputStream, "test.png", "image/png", metaData).getId().toString();
	}
	
	public void findOneFs(){
		String id = "5602de6e5d8bba0d6f2e45e4";
		GridFSDBFile gridFsdbFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id)));
		List<GridFSDBFile> gridFSDBFiles = gridFsTemplate.find(null);
		List<GridFSDBFile> gridFsdbFiles = 
				  gridFsTemplate.find(new Query(Criteria.where("metadata.user").is("alex")));

	}
	
	public void deleteFs(){
		String id = "5702deyu6d8bba0d6f2e45e4";
		gridFsTemplate.delete(new Query(Criteria.where("_id").is(id)));
	}
	
	
}
